package cn.le.api;

import cn.le.quartz.QuartzExectueJob;
import io.swagger.annotations.ApiOperation;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping
public class QuartzController {

    @Autowired
    private Scheduler scheduler ;

    @ApiOperation(value="添加任务,默认添加一个调度器", notes="添加任务")
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String add() throws SchedulerException {
        JobKey jobKey = new JobKey("jobKey-1");
        TriggerKey triggerKey = new  TriggerKey("triggerKey-1");
        JobDetail jobDetail = JobBuilder.newJob(QuartzExectueJob.class)
                .withIdentity(jobKey)
                .build();
        CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule("/5 * * * * ? ");
        Trigger trigger = TriggerBuilder.newTrigger().withIdentity(triggerKey)
                .withSchedule(cronScheduleBuilder).build();
        scheduler.scheduleJob(jobDetail,trigger);
        return "创建成功！";
    }


    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public String update() throws SchedulerException {
        TriggerKey triggerKey = new  TriggerKey("triggerKey-1");
        CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule("/3 * * * * ? ");
        Trigger trigger = TriggerBuilder.newTrigger().withIdentity(triggerKey)
                .withSchedule(cronScheduleBuilder).build();
        scheduler.rescheduleJob(triggerKey,trigger);
        return "修改成功！";
    }


    @RequestMapping(value = "/queryJobTrigger", method = RequestMethod.POST)
    public String queryJobTrigger() throws SchedulerException {
        JobKey jobKey = new JobKey("jobKey-1");
        List<? extends Trigger> triggersOfJob = scheduler.getTriggersOfJob(jobKey);
        StringBuilder stringBuilder = new StringBuilder();
        triggersOfJob.forEach(trigger->{
            stringBuilder.append(trigger.getKey().getName()).append("\n");
        });
        return stringBuilder.toString();
    }




}
